package com.zlz.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zlz.server.config.security.JwtTokenUtil;
import com.zlz.server.constant.ErrorCodeConstant;
import com.zlz.server.exception.YebException;
import com.zlz.server.mapper.AdminMapper;
import com.zlz.server.mapper.AdminRoleMapper;
import com.zlz.server.mapper.RoleMapper;
import com.zlz.server.pojo.Admin;
import com.zlz.server.pojo.AdminRole;
import com.zlz.server.pojo.RespBean;
import com.zlz.server.pojo.Role;
import com.zlz.server.service.IAdminService;
import com.zlz.server.utils.AdminUtil;
import com.zlz.server.utils.ParamUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author efire
 * @since 2021-01-16
 */
@Service
@Slf4j
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {
    @Resource
    private UserDetailsService userDetailsService;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Resource
    private AdminMapper adminMapper;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private AdminRoleMapper adminRoleMapper;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Override
    public RespBean login(String username, String password, String code, HttpServletRequest httpServletRequest) {
        String storedCaptcha = (String) httpServletRequest.getSession().getAttribute("captcha");
        log.info("storedCaptcha:" + storedCaptcha);
        // 校验验证码
        if (StringUtils.isEmpty(storedCaptcha) || !code.equalsIgnoreCase(storedCaptcha)) {
            return RespBean.error("验证码错误");
        }
        // 登录
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        System.out.println(passwordEncoder.encode(password));
        if (userDetails == null || !passwordEncoder.matches(password, userDetails.getPassword())) {
            return RespBean.error("用户名或密码不正确");
        }
        if (!userDetails.isEnabled()) {
            return RespBean.error("账号已被禁用，请联系管理员！");
        }

        // 更新security登录用户对象
        UsernamePasswordAuthenticationToken authenticationToken = new
                UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        // 生成token
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return RespBean.success("登录成功", tokenMap);
    }

    @Override
    public Admin getAdminByUserName(String username) {
        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username", username)
                .eq("enabled", true));
    }

    @Override
    public List<Role> getRolesByAdminId(Long id) {
        return roleMapper.getRolesByAdminId(id);
    }

    @Override
    public List<Admin> getAllOperates(String keywords) {
        return adminMapper.getAllAdmins(AdminUtil.getCurrentAdmin().getId(), ParamUtil.dealSpecialString(keywords));
    }

    @Override
    @Transactional
    public RespBean updateAdminRole(Long adminId, Long[] rids) {
        adminRoleMapper.delete(new QueryWrapper<AdminRole>().eq("admin_id", adminId));
        adminRoleMapper.insertAdminRole(adminId, rids);
        return RespBean.success();
    }

    @Override
    public void updateAdminPwd(String oldPwd, String pwd, String adminId) {
        Admin admin = adminMapper.selectById(adminId);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (!encoder.matches(oldPwd, admin.getPassword())) {
            log.error("密码错误");
           throw new YebException(ErrorCodeConstant.PWD_ERROR, "密码错误");
        }
        admin.setPassword(encoder.encode(pwd));
        adminMapper.updateById(admin);
    }
}
